package com.fzebu.fastboot.docs.file;

import com.itextpdf.text.DocumentException;
import lombok.Getter;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jack
 * @version 1.0.0
 * @create 2020/1/20 12:47
 */
public class FileHandler {

    private final Builder builder;

    private FileHandler(Builder builder) {
        this.builder = builder;
    }

    public void convert(IConvert iConvert, ProcessHandler processHandler) {
        try {
            if (processHandler != null) {
                for (File file : builder.files) {
                    processHandler.handler(file);
                }
            }
            iConvert.convert(builder);
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }

    @Getter
    public static class Builder {

        private List<File> files;

        private String destPath;

        public Builder of(String filePath) {
            File file = new File(filePath);
            return of(file);
        }

        public Builder of(File file) {
            if (!file.exists()) {
                throw new IllegalStateException("file is not exists");
            }
            if (this.files == null) {
                this.files = new ArrayList<>();
            }
            if (file.isDirectory()) {
                File[] fileArr = file.listFiles();
                if (fileArr != null && fileArr.length > 0) {
                    this.files.addAll(Arrays.asList(fileArr));
                }
            } else {
                this.files.add(file);
            }
            return this;
        }

        public Builder destPath(String destPath) {
            this.destPath = destPath;
            return this;
        }

        public Builder destName(String destName) {
            this.destPath = destPath + File.separator + destName;
            return this;
        }

        public boolean checkFiles() {
            return this.files != null && this.files.size() != 0;
        }

        public FileHandler build() {
            if (StringUtils.isEmpty(this.destPath)) {
                throw new IllegalStateException("destPath is null");
            }
            return new FileHandler(this);
        }
    }

    public interface ProcessHandler {

        void handler(File file) throws IOException;
    }
}
